/*
 * Copyright 2021 liqiang
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.jansen.download.core;


import org.jansen.download.DownloadConfig;
import org.jansen.download.utils.Logger;

import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * modified by liqiang  2021-08-20
 */
public class ConnectThread implements Runnable {

    private static final String TAG = ConnectThread.class.getSimpleName();

    private final    String          mUrl;
    private final    ConnectListener mListener;
    private volatile boolean         isRunning;
    private volatile boolean         isError;
    private final    AtomicInteger   mRetryCount = new AtomicInteger();
    private DownloadConfig mDownloadConfig;

    public ConnectThread(DownloadConfig downloadConfig, String url, ConnectListener listener) {
        this.mDownloadConfig = downloadConfig;
        this.mUrl = url;
        this.mListener = listener;
    }

    @Override
    public void run() {
        Logger.w(TAG, "isRetry: [" + (mRetryCount.get() >= 1) + "]");
        isRunning = true;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(mDownloadConfig.getConnTimeMillis(), TimeUnit.MILLISECONDS)
                .readTimeout(mDownloadConfig.getReadTimeoutMillis(), TimeUnit.MILLISECONDS)
                .callTimeout(mDownloadConfig.getCallTimeMillis(), TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .url(mUrl)
                .addHeader("Connection", "close")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            int responseCode = response.code();
            String contentLengthStr = response.header("content-length");
            int contentLength = 0;
            try {
                contentLength = Integer.parseInt(contentLengthStr);
            } catch (Exception e) {
            }

            boolean isSupportRange = false;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String ranges = response.header("Accept-Ranges");
                if ("bytes".equals(ranges)) {
                    isSupportRange = true;
                }
                mListener.onConnected(isSupportRange, contentLength);
            } else {
                mListener.onConnectError("server ERROR:" + responseCode);
            }
            isRunning = false;
        } catch (Throwable e) {
            isError = true;
            isRunning = false;
            mListener.onConnectError(e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
            if (isError) {
                if (mRetryCount.getAndIncrement() < mDownloadConfig.getMaxRetryCount()) {
                    Logger.w(TAG, "RetryCount:" + mRetryCount.get());
                    try {
                        Thread.sleep(mDownloadConfig.getRetryIntervalMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    run();
                }
            }

        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    interface ConnectListener {
        void onConnected(boolean isSupportRange, int totalLength);

        void onConnectError(String message);
    }
}

